Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

206
Views
Cómo solucionar el problema en mi código de algoritmo "isParenthesisValid"

Estoy resolviendo una pregunta de algoritmo que requiere que me asegure de que los corchetes, paréntesis y llaves se coloquen en el orden o secuencia correctos.

Aquí hay un enlace a la pregunta, https://leetcode.com/problems/valid-parentheses/

A continuación se muestra un ejemplo:

condiciones para determinar si el patrón es correcto o no

Aquí está mi código para la solución:

 const isParenthesisValid = (params) => { myList = [] lastElement = myList[myList.length - 1] for (let i = 0; i < params.length; i++) { if (params[i] === "(" || params[i] === "[" || params[i] === "{" ) { myList.push(params[i]) } else if ((params[i] === ")" && lastElement === "(") || (params[i] === "]" && lastElement === "[") || (params[i] === "}" && lastElement === "{")) { myList.pop() } else return false } return myList.length ? false : true } // I get false as an answer everytime whether the pattern is correct or wrong // false console.log(isParenthesisValid("[()]"))

Pero no sé por qué siempre obtengo falso, comparé mi respuesta con la respuesta de otra persona que hizo lo mismo, pero parece que estoy omitiendo algo que no es tan obvio.

Espero que alguien pueda señalar en mi código dónde me estoy equivocando.

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

Su lastElement recupera el último elemento de la lista al comienzo del programa , cuando no existe tal elemento, por lo que siempre está undefined . En su lugar, debe recuperar el valor dentro del bucle.

 const isParenthesisValid = (params) => { myList = [] for (let i = 0; i < params.length; i++) { const lastElement = myList[myList.length - 1] if (params[i] === "(" || params[i] === "[" || params[i] === "{" ) { myList.push(params[i]) } else if ((params[i] === ")" && lastElement === "(") || (params[i] === "]" && lastElement === "[") || (params[i] === "}" && lastElement === "{")) { myList.pop() } else return false } return myList.length ? false : true } console.log(isParenthesisValid("[()]"))

O, un poco más legible:

 const isParenthesisValid = (input) => { const openDelimiters = []; for (const delim of input) { const lastElement = openDelimiters[openDelimiters.length - 1]; if (delim === "(" || delim === "[" || delim === "{") { openDelimiters.push(delim) } else if ((delim === ")" && lastElement === "(") || (delim === "]" && lastElement === "[") || (delim === "}" && lastElement === "{")) { openDelimiters.pop() } else return false } return openDelimiters.length === 0; } console.log(isParenthesisValid("[()]"))

Otro enfoque, vinculando cada delimitador con un objeto:

 const delims = { ')': '(', '}': '{', ']': '[', }; const isParenthesisValid = (input) => { const openDelimiters = []; for (const delim of input) { if ('([{'.includes(delim)) { openDelimiters.push(delim) } else if (')]}'.includes(delim) && openDelimiters[openDelimiters.length - 1] === delims[delim]) { openDelimiters.pop() } else return false } return openDelimiters.length === 0; } console.log(isParenthesisValid("[()]"))

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!